package network;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import controller.GUIController;
import controller.UDPServerController;

import itdb1.commun.*;

public class UDPChatNIServer extends ChatNIServer {

	private GUIController guicontroller;
	
	protected DatagramSocket listeningSocket;
	protected int port;
	private boolean isrunning;
	
	public UDPChatNIServer(int port) {
		super( UDPServerController.getInstance() );
		this.guicontroller = GUIController.getInstance();
		this.port = port;
	}

	@Override
	public void run() {
		isrunning = true;
		
		try
		{
			listeningSocket = new DatagramSocket(port);
			// tous les 500 millisecondes, si aucun client ne se présente, on stope le receive() pour vérifier si on a pas reçu l'ordre de shutdown
			//listeningSocket.setSoTimeout(500);
			
			byte[] buffer = new byte[NetworkSettings.UDP_BUFFER_SIZE];
			DatagramPacket datagram;
			NetworkSignal message;
			
			guicontroller.writeDebugScreen("UDPChatNIServer > Waiting for datagrams\n");
			
			do
			{
				datagram = new DatagramPacket(buffer, buffer.length);
				try
				{
					listeningSocket.receive(datagram);
					
					message = (NetworkSignal) (new ObjectInputStream(new ByteArrayInputStream(datagram.getData()))).readObject();
					message.setFromIp(datagram.getAddress());
					
					((UDPServerController) this.controller).messages.add(message);
				}
				catch(SocketException socketException)
				{
					//socketException.printStackTrace();
					guicontroller.writeDebugScreen("UDPChatNIServer > shut down\n");
				}
				catch(IOException ioException)
				{
					ioException.printStackTrace();
					guicontroller.writeDebugScreen("UDPChatNIServer > A message has been discarded because of an I/O error.\n");
				}
				catch(ClassNotFoundException weirdObjectException)
				{
					//weirdObjectException.printStackTrace();
					guicontroller.writeDebugScreen("UDPChatNIServer > Bad object received !\n");
				}
			} while(isrunning);
		}
		catch(SecurityException securityException)
		{
			securityException.printStackTrace();
		}
		catch(SocketException socketException)
		{
			socketException.printStackTrace();
			guicontroller.writeDebugScreen("UDPChatNIServer > The port " + port + " is already in use.\n");
		}
	}
	
	public void kill()
	{
		isrunning = false;
		listeningSocket.close();
	}
}
